<script setup lang="ts">
import { ref, reactive, getCurrentInstance } from "vue";

import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";

import upload from "@iconify-icons/ep/upload";
import Refresh from "@iconify-icons/ep/refresh";
import { Plus } from "@element-plus/icons-vue";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { genFileId } from "element-plus";
import AppUtil from "@/utils/AppUtil";

import AddFill from "@iconify-icons/ri/add-circle-line";
import { useRoute } from "vue-router";
import Edit from "@iconify-icons/ep/edit";
//import log from "./comp/log.vue";
import Form from "@/components/Form.vue";
const route = useRoute();
defineOptions({
  name: "gq"
});
const config = reactive({
  listUrl: "/crm/gq/index?crm_state=4",
  addUrl: "",
  editUrl: "/crm/setRemark?from=3",
  deleteUrl: "/crm/pickUp?from=3",
  detailUrl: "",
  title: "股权",

  /**搜索条件 */
  searchForm: [
    {
      label: "状态",
      prop: "state",
      type: "select",
      options: [
        { id: "", name: "不限" },
        { id: "1", name: "发布中" },
        { id: "2", name: "已完成" }
      ]
    },
    {
      label: "发布类型",
      prop: "type",
      type: "select",
      options: [
        { id: "", name: "不限" },
        { id: "1", name: "收购" },
        { id: "2", name: "出让" }
      ]
    },
    {
      label: "安全许可状态",
      prop: "aqxkz_state",
      type: "select",
      options: [
        { id: "", name: "不限" },
        { id: "1", name: "有" },
        { id: "2", name: "无" },
        { id: "3", name: "过期" }
      ]
    },

    {
      label: "发布时间",
      prop: "created_at",
      type: "datetimerange"
    },

    {
      label: "联系人",
      prop: "lxr_name",
      type: "input",
      input: {
        type: "text"
      }
    },
    {
      label: "联系手机",
      prop: "lxr_tel",
      type: "input",
      input: {
        type: "text"
      }
    }
  ],
  /**
   * 添加/编辑表单
   */
  editForm: [
    //备注 remark
    {
      label: "添加备注",
      prop: "remark",
      type: "textarea",
      textarea: {
        type: "textarea",
        rows: 4,
        placeholder: "请输入备注"
      },
      span: 24,
      value: "",
      rules: [
        {
          required: true,
          message: "请输入备注",
          trigger: "blur"
        }
      ]
    }
  ],
  rules: {},
  formData: {},
  defaultData: {},

  /**
   * 表格列
   */
  columns: [
    {
      label: "id",
      prop: "id",
      width: 80,
      fixed: "left"
    },
    {
      label: "发布人ID",
      prop: "qy_zh_id",
      width: 80
    },
    {
      label: "发布类型",
      prop: "type_label",
      width: 100,
      fixed: "left"
    },
    {
      label: "注册地",
      prop: "yyzz_zc_address_code_name",
      width: 130
    },
    {
      label: "安全许可证",
      prop: "aqxkz_fz_tim",
      minWidth: 130,
      slot: "aqxkz"
    },
    {
      label: "价格",
      prop: "price_min",
      minWidth: 130,
      slot: "price"
    },
    {
      label: "联系人",
      prop: "lxr_name",
      minWidth: 100
    },
    {
      label: "联系电话",
      prop: "lxr_tel",
      minWidth: 100
    },
    {
      label: "加急",
      prop: "is_jj",
      width: 80,
      slot: "jj",
      fixed: "left"
    },
    {
      label: "股权整转",
      prop: "is_gqzz",
      width: 80,
      slot: "gqzz"
    },
    {
      label: "资质证书",
      prop: "zzzs_type_label",
      minWidth: 200
    },
    {
      label: "支付信息",
      prop: "pay_time",
      width: 180,
      slot: "pay"
    },
    {
      label: "发证时间",
      prop: "fz_time",
      width: 180
    },
    {
      label: "到期时间",
      prop: "dq_time",
      width: 180
    },
    {
      label: "完成时间",
      prop: "finish_time",
      width: 180
    },
    {
      label: "备注",
      prop: "remark"
    },
    {
      label: "状态",

      prop: "state_label",
      width: 80
    },
    {
      label: "操作",
      fixed: "right",
      width: 120,
      slot: "operation"
    }
  ]
});

const pData = reactive({
  /**
   * 表格数据
   */
  dataArr: [],
  /**
   * 表格加载
   */
  loading: false,
  /**请求中 */
  reqing: false,
  /**
   * 表格分页
   */
  pagination: {
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  },

  imgArr: [],
  searchData: {},
  showEdit: false,

  showLog: false,
  id: ""
});

// const formData = reactive({
//   name: "",
//   category_id: "",

//   sort: "1",

//   id: ""
// });
const rules = {
  sort: [
    {
      required: true,
      message: "字段值不可为空"
    },
    {
      pattern: /^[-]?\d+(\.\d+)?$/,
      trigger: ["blur", "change"],
      message: "请输入数字"
    }
  ],

  name: [
    {
      required: true,
      message: "标题不能为空",
      trigger: ["blur"]
    }
  ],

  category_id: [
    {
      required: true,
      message: "分类不能为空",
      trigger: "blur"
    }
  ]
};

const instance = getCurrentInstance();
function update_click(item) {
  config.formData = item;
  // pData.imgArr = [
  //   {
  //     url: AppUtil.getAliImgUrlByH(item[config.imgKey]),
  //     response: { code: 200, data: item[config.imgKey] }
  //   }
  // ];
  config.editForm.map(item1 => {
    //处理封面初始化imgArr

    if (item1.type == "uploadOne") {
      item1.imgArr = [
        {
          url: AppUtil.getAliImgUrlByH(item[item1.prop]),
          response: { code: 200, data: item[item1.prop] }
        }
      ];
    }
  });
  // config.editForm=JSON.parse(JSON.stringify(config.editForm));
  console.log("update_click editForm", config.editForm);

  pData.showEdit = true;
}
function add_click() {
  if (config.formData.id) {
    //移除选中的编辑数据，保留上次新增数据
    config.formData = JSON.parse(JSON.stringify(config.defaultData));
    config.editForm.map(item1 => {
      //处理封面初始化imgArr
      if (item1.type == "uploadOne") {
        item1.upload.fileArr = [];
      }
    });
  }

  // config.editForm=JSON.parse(JSON.stringify(config.editForm));
  pData.showEdit = true;
}
const upload1 = ref<UploadInstance>();
const handleExceed: UploadProps["onExceed"] = files => {
  upload_one(upload1, files);
};
const upload_one = (upload, files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
  upload.value!.submit();
};
const upload_ok = (response, uploadFile, key) => {
  console.log("upload_ok", response, uploadFile);
  // console.log("filelist", pData.imgArr);

  if (response.code == 200) {
    uploadFile.status = "success";
    config.formData[key] = response.data;
  } else {
    uploadFile.status = "fail";
    instance.proxy.$message.error(response.msg || "上传失败");
  }
};
function handleSizeChange(val: number) {
  console.log(`${val} items per page`);
  pData.pagination.pageSize = val;
  reset_list();
}

function handleCurrentChange(val: number) {
  console.log(`current page: ${val}`);
  pData.pagination.currentPage = val;
  onSearch();
}
//请求轮播图数据
async function onSearch() {
  pData.loading = true;

  AppUtil.request(
    {
      url: config.listUrl,
      method: "get",
      params: {
        ...pData.searchData,
        current: pData.pagination.currentPage,
        size: pData.pagination.pageSize
      }
    },
    res => {
      res.data.data.map(item => {
        let imgArr = [];
        let bigArr = [];
        item.pg_hb &&
          item.pg_hb.map(item1 => {
            imgArr.push(AppUtil.getAliImgUrlByW(item1, 200));
            bigArr.push(AppUtil.imgHost + item1);
          });
        item.imgArr = imgArr;
        item.bigArr = bigArr;
      });
      pData.dataArr = res.data.data;
      pData.pagination.total = res.data.total;
      pData.pagination.currentPage = res.data.current_page;
    },
    b => (pData.loading = false)
  );
}
onSearch();

function search_click() {
  reset_list();
}
/**搜索第一页的数据 */
function reset_list() {
  pData.pagination.currentPage = 1;
  onSearch();
}
function submitForm() {
  submit_form();
  // if (pData.imgArr.length < 1) {
  //   return instance.proxy.$alert("请选择图片");
  // }
  // let img = pData.imgArr[0];
  // //图片已经上传过
  // if (img.response && img.response.code == 200) {
  //   return submit_form();
  // }
  // //上传图片
  // upload1.value!.submit();
}
/**
 * 提交表单
 */
function submit_form() {
  instance.proxy.$refs["vForm"].validate(valid => {
    if (!valid) return;
    pData.reqing = true;

    // return console.log('formData',formData);

    AppUtil.request(
      {
        url: config.formData.id ? config.editUrl : config.addUrl,
        method: "post",
        data: config.formData
      },
      res => {
        // console.log("banner", res);
        instance.proxy.$message.success(
          config.formData.id ? "修改成功" : "添加成功"
        );
        onSearch();
        pData.showEdit = false;
      },
      b => {
        pData.reqing = false;
      }
    );
  });
}

function log_click(item) {
  pData.showLog = true;
  pData.id = item.id;
}
</script>

<template>
  <div class="main">
    <el-form
      :model="pData.searchData"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
      style="padding-bottom: 5px"
      :inline="true"
    >
      <el-form-item
        v-for="(item, i) in config.searchForm"
        :key="i"
        :label="item.label"
        :prop="item.prop"
      >
        <el-select
          v-if="item.type === 'select'"
          v-model="pData.searchData[item.prop]"
          style="width: 200px"
          placeholder="请选择"
        >
          <el-option
            v-for="(option, j) in item.options"
            :key="j"
            :label="option.label || option.name"
            :value="option.value || option.id"
          />
        </el-select>
        <el-input
          v-else-if="item.type === 'input'"
          v-model="pData.searchData[item.prop]"
          :placeholder="item.input.placeholder"
          clearable
        />
        <el-date-picker
          v-else-if="item.type === 'datetimerange'"
          v-model="pData.searchData[item.prop]"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 360px"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="pData.loading"
          @click="search_click"
        >
          搜索
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar
      :title="config.title + '管理'"
      :columns="config.columns"
      @refresh="onSearch"
    >
      <template #buttons>
        <el-button
          v-if="config.addUrl"
          type="primary"
          :icon="useRenderIcon(upload)"
          @click="add_click"
        >
          新增{{ config.title }}
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          :data="pData.dataArr"
          :columns="dynamicColumns"
          :loading="pData.loading"
          :size="size"
          :pagination="pData.pagination"
          :paginationSmall="size === 'small' ? true : false"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #pay="{ row, index }">
            <div v-if="row.pay_price">
              <div>支付金额:{{ row.pay_price }}</div>
              <div>支付时间:{{ row.pay_time }}</div>
              <div>微信单号:{{ row.pay_wx_id }}</div>
            </div>
            <div v-else>/</div>
          </template>
          <template #aqxkz="{ row, index }">
            <div v-if="row.aqxkz_state == 1">
              <div>发证时间:{{ row.aqxkz_fz_time }}</div>
              <div>到期时间:{{ row.aqxkz_dq_time }}</div>
            </div>
            <div v-else>/</div>
          </template>

          <template #price="{ row, index }">
            {{ row.price_min }} - {{ row.price_max }}
          </template>
          <template #jj="{ row, index }">
            {{ row.is_jj * 1 == 1 ? "是" : "否" }}
          </template>
          <template #gqzz="{ row, index }">
            {{ row.is_gqzz * 1 == 1 ? "是" : "否" }}
          </template>
          <template #operation="{ row }">
            <!-- <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                  :icon="useRenderIcon(AddFill)"
                  @click="log_click(row)"
                >
                跟进记录
                </el-button>
                <el-popconfirm
              title="是否捡回？"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                  :icon="useRenderIcon(Delete)"
                >
                  捡回
                </el-button>
              </template>
            </el-popconfirm> -->

            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(Edit)"
              @click="update_click(row)"
              >添加备注</el-button
            >
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <el-dialog
      v-model="pData.showEdit"
      align-center
      :title="`${config.formData.id ? '修改' : '新增'}${config.title}`"
      :width="700"
      draggable
    >
      <div style="max-height: 82vh; overflow-y: auto; padding-right: 1.5rem">
        <Form ref="vForm" v-model="config" />
      </div>

      <template #footer>
        <div class="cls-center">
          <el-button @click="pData.showEdit = false">取消</el-button>
          <el-button
            type="primary"
            :loading="pData.reqing"
            @click="submitForm()"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="pData.showLog"
      align-center
      title="查看记录"
      width="80vw"
      draggable
    >
      <!--<div style="max-height: 82vh; overflow-y: auto; padding: 0 1rem">
        <log :id="pData.id" v-if="pData.showLog" f="3"></log>
      </div> -->

      <template #footer>
        <div class="cls-center">
          <el-button @click="pData.showLog = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
